﻿using System;

namespace OpenLS.Spreadsheet.Expressions
{
    class FullRowRangeReference : FullRangeReference<Row, Column>
    {
        public FullRowRangeReference(DimensionReference<Row, Column> first, DimensionReference<Row, Column> last) : base(first, last)
        {
        }

        protected override void OnRangeDeleting(RangeChangeEventArgs e)
        {
            if (e.Hint == CellMoveOrientationHint.Vertical)
            {
                if (e.Address.IsFullRow)
                {
                    if (e.Address.Contains(new CellAddress(First.Anchor.Index, 0)))
                    {
                        int offset = e.Address.BottomRight.Row - First.Anchor.Index + 1;
                        offset = Math.Max(offset, -First.Anchor.Index);
                        First = First.OffsetDim(new CellRelativeAddress(offset, 0));
                    }
                    if (e.Address.Contains(new CellAddress(Last.Anchor.Index, 0)))
                    {
                        int offset = e.Address.TopLeft.Row - Last.Anchor.Index - 1;
                        offset = Math.Max(offset, -Last.Anchor.Index);
                        Last = Last.OffsetDim(new CellRelativeAddress(offset, 0));
                    }
                }
            }
        }

        public override int MinRowIndex
        {
            get { return First.Anchor.Index; }
        }

        public override int MaxRowIndex
        {
            get { return Last.Anchor.Index; }
        }

        public override int MinColumnIndex
        {
            get { return 0; }
        }

        public override int MaxColumnIndex
        {
            get { return Worksheet.MaxColumnIndex; }
        }

        public override RangeReference Offset(CellRelativeAddress address)
        {
            DimensionReference<Row, Column> newFirst = First.OffsetDim(address);
            DimensionReference<Row, Column> newLast = Last.OffsetDim(address);
            return new FullRowRangeReference(newFirst, newLast);
        }

        internal override RangeReference Transposed(Cell target)
        {
            return new FullColumnRangeReference(First.Transposed<Column>(target), Last.Transposed<Column>(target));
        }

        internal override RangeReference Projected(Worksheet targetWorksheet)
        {
            return new FullRowRangeReference(((RowReference)First).Projected(targetWorksheet), ((RowReference)Last).Projected(targetWorksheet));
        }
    }
}